package com.zookeeper.basic.one;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by 58 on 2016-7-17.
 * 使用同步API获取节点内容
 */
public class ZkGetDataAysc implements Watcher{
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;
    private static  Stat stat = new Stat();//传入参数，会从服务器获取最新的状态信息

    public void process(WatchedEvent event) {
        if(Event.KeeperState.SyncConnected == event.getState()){
            if(Event.EventType.None == event.getType() && null == event.getPath()){
                countDownLatch.countDown();
            }
            //数据内容或者是数据版本的变化都会触发服务端的NodeDataChanged通知
            else if(event.getType() == Event.EventType.NodeDataChanged){   //节点变更后会有提示
                try {
                    System.out.println(new String(zooKeeper.getData(event.getPath(),true,stat)));
                    System.out.println(stat.getCzxid()+"---"+stat.getMzxid()+"---"+stat.getVersion());
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181",5000,new ZkGetDataAysc());
        countDownLatch.await();
        zooKeeper.create(path,"123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(new String(zooKeeper.getData(path,true,stat)));
        System.out.println(stat.getCzxid()+"---"+stat.getMzxid()+"---"+stat.getVersion());
        zooKeeper.setData(path,"1234".getBytes(),-1);
        Thread.sleep(Integer.MAX_VALUE);
    }

}
